// app.ts
const _config = require('utils/config'); // 加载配置文件
const _request = require('utils/ajax'); // 加载封装request请求
App<IAppOption>({
  globalData: {},
  onLaunch() {
    wx.removeStorageSync('loginInfo')
    // 获取右上角胶囊信息
    let capsule = wx.getMenuButtonBoundingClientRect();
    this.globalData.capsule = capsule;
    // wx.updateWeChatApp()
    // 登录
    wx.login({
      success: (res: any) => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        if (this.userInfoReadyCallback) {
          this.userInfoReadyCallback(res)
        }
      },
    })
  },
  /**
 * 获取个人信息如果不存在则调用登陆接口
 * @param {*} callBack 
 * @param {*} errorCallback 
 * @param {*} type 
 */
  toLogin(callBack: any): any {
    const _that = this;
    let user_info: any = false;
    try {
      user_info = wx.getStorageSync('loginInfo') ? wx.getStorageSync('loginInfo') : _that.globalData.loginInfo;
    } catch {
    }
    if (user_info) {
      _that.loginCallback(user_info, callBack);
      return true;
    } else {
      _that.wxLogin(() => {
        _request({
          url: 'weixin/login',
          data: {
            code: _that.globalData.jsCode
          },
          is_loading: {
            status: true,
            title: '加载中',
            hideShow: false
          },
          success: (res: any) => {
            _that.globalData.loginInfo = res;
            wx.setStorageSync('loginInfo', res);
            wx.setStorageSync('openid', res.openid);
            _that.loginCallback(res, callBack);
          },
          error: (res: any) => {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              mask: true,
              duration: 2000
            })
          }
        })
      })

    }
  },
  loginCallback(user_info: any, callBack: any) {
    if (typeof callBack == "function") {
      callBack(user_info);
    } else if (typeof this.userInfoReadyCallback == 'function') {
      this.userInfoReadyCallback(user_info);
      this.userInfoReadyCallback = undefined;
    }
  },
  wxLogin(successFun: any) {
    wx.login({
      success: (res) => {
        // 发送 res.code 到后台换取 openId, jsCode, unionId
        this.globalData.jsCode = res.code;
        typeof successFun == 'function' && successFun(res);
      },
      fail: () => {

      }
    });
  },
  onSaveExitState():any{

  }
})